package com.example.library.service;

import com.example.library.entity.Book;
import com.example.library.entity.BorrowRecord;
import com.example.library.entity.Student;
import com.example.library.repository.BookRepository;
import com.example.library.repository.BorrowRecordRepository;
import com.example.library.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDateTime;

@Service
public class BorrowService {

    @Autowired
    private BookRepository bookRepository;

    @Autowired
    private StudentRepository studentRepository;

    @Autowired
    private BorrowRecordRepository borrowRecordRepository;

    @Transactional
    public BorrowRecord borrowBook(Long studentId, Long bookId) {
        Student student = studentRepository.findById(studentId)
                .orElseThrow(() -> new RuntimeException("学生不存在"));
        Book book = bookRepository.findById(bookId)
                .orElseThrow(() -> new RuntimeException("图书不存在"));

        if (book.getStock() <= 0) {
            throw new RuntimeException("库存不足");
        }

        book.setStock(book.getStock() - 1);
        bookRepository.save(book);

        BorrowRecord record = new BorrowRecord();
        record.setStudent(student);
        record.setBook(book);
        record.setBorrowTime(LocalDateTime.now());
        return borrowRecordRepository.save(record);
    }

    @Transactional
    public void returnBook(Long recordId) {
        BorrowRecord record = borrowRecordRepository.findById(recordId)
                .orElseThrow(() -> new RuntimeException("借阅记录不存在"));

        if (record.getIsReturned()) {
            throw new RuntimeException("该书已归还");
        }

        Duration duration = Duration.between(record.getBorrowTime(), LocalDateTime.now());
        long daysOverdue = duration.toDays() - 30; // 假设借期为30天
        if (daysOverdue > 0) {
            record.setFineAmount(daysOverdue * 0.5); // 每天罚款0.5元
        }

        record.setIsReturned(true);
        record.setReturnTime(LocalDateTime.now());
        borrowRecordRepository.save(record);

        Book book = record.getBook();
        book.setStock(book.getStock() + 1);
        bookRepository.save(book);
    }
}